<template>
  <el-dialog
    v-model="visible"
    title="屏蔽区域管理"
    width="85%"
    top="5vh"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @open="onDialogOpen"
    class="mask-area-dialog"
  >
    <el-container v-loading="isLoading" class="dialog-container">
      
      <el-aside width="350px" class="aside-panel">
        <div class="aside-header">
          <el-button 
            type="primary" 
            :icon="Plus" 
            @click="handleStartNew"
            :disabled="isDrawingMode"
          >
            新建屏蔽区域
          </el-button>
        </div>
        
        <el-table
          :data="maskAreas"
          highlight-current-row
          height="calc(80vh - 100px)"
          class="area-table"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="name" label="区域名称" />
          
          <el-table-column label="操作" width="140">
            <template #default="{ row }">
              <el-button
                :type="visibleAreaIds.has(row.id) ? 'success' : ''"
                :icon="visibleAreaIds.has(row.id) ? Hide : View"
                size="small"
                circle
                @click.stop="toggleAreaVisibility(row)"
                :title="visibleAreaIds.has(row.id) ? '隐藏多边形' : '显示多边形'"
              />
              
              <el-button
                type="primary"
                :icon="DataAnalysis"
                size="small"
                circle
                @click.stop="handleViewVertexData(row)"
                title="查看顶点数据"
              />
              
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                circle
                @click.stop="handleDeleteArea(row)"
                title="删除"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-aside>

      <el-main class="main-panel">
        <div v-if="isDrawingMode" class="drawing-controls">
          <el-form :model="form" inline>
            <el-form-item label="区域名称" required>
              <el-input v-model="form.name" placeholder="请输入新区域名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="success" :icon="Check" @click="handleSaveDrawing" :disabled="currentDrawingVerticesReal.length < 3 || form.name === ''">确定保存</el-button>
              <el-button :icon="RefreshLeft" @click="clearDrawing" :disabled="currentDrawingVerticesPx.length === 0">清空重画</el-button>
              <el-button :icon="Close" @click="handleCancelDrawing">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-else class="view-controls">
          <span>当前已显示 <b>{{ visibleAreaIds.size }}</b> 个区域。请点击列表中的“眼睛”按钮进行查看。</span>
        </div>
        <div class="drawing-container" ref="containerRef">
          <img src="/边坡监测范围.png" ref="imageRef" class="background-image" @load="updateImageDimensions" />
          <svg class="drawing-overlay" v-if="imgRenderedWidth > 0" :width="imgRenderedWidth" :height="imgRenderedHeight" @click="handleDrawClick" :class="{ 'is-drawing': isDrawingMode }">
            <polygon v-for="(polygon, index) in displayedPolygonPoints" :key="'view-' + polygon.id" :points="polygon.points" class="polygon-view" :style="{ stroke: polygon.color, fill: polygon.color + '4D' }" />
            <polygon :points="currentDrawingPolygonPoints" class="polygon-draw" />
            <circle v-for="(v, index) in currentDrawingVerticesPx" :key="'draw-' + index" :cx="v.x" :cy="v.y" :r="index === 0 ? 5 : 4" :class="index === 0 ? 'vertex-start' : 'vertex-point'" @click.stop="handleVertexClick(index)" />
          </svg>
        </div>
      </el-main>
    </el-container>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="vertexDataDialogVisible"
    :title="`顶点数据: ${currentDataAreaName}`"
    width="40%"
    append-to-body
  >
    <el-table :data="currentVertexData" height="400px" border>
      <el-table-column prop="x" label="X 坐标" :formatter="formatCoordinate" />
      <el-table-column prop="y" label="Y 坐标" :formatter="formatCoordinate" />
    </el-table>
  </el-dialog>

</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Plus, Delete, Check, Close, RefreshLeft, 
  View, Hide, DataAnalysis // **已修改**: 用 DataAnalysis 替换 DataLine
} from '@element-plus/icons-vue';
import axios from 'axios';

// --- 接口数据类型 ---
interface Vertex {
  x: number;
  y: number;
}
interface MaskArea {
  id: number;
  name: string;
  vertices: Vertex[];
}

// 随机颜色列表 (不变)
const COLORS = [
  '#FF9800', '#4CAF50', '#2196F3', '#9C27B0', 
  '#F44336', '#FFEB3B', '#00BCD4', '#E91E63'
];

// --- Dialog 状态 (不变) ---
const visible = ref<boolean>(false);
const isLoading = ref<boolean>(false);
const isDrawingMode = ref<boolean>(false);
const form = ref({ name: "" });

// --- 坐标映射常量 (不变) ---
const REAL_X_MIN = 2369500;
const REAL_X_MAX = 2372400;
const REAL_Y_MIN = 771600;
const REAL_Y_MAX = 774000;
const REAL_WIDTH = REAL_X_MAX - REAL_X_MIN;
const REAL_HEIGHT = REAL_Y_MAX - REAL_Y_MIN;

// --- 绘图状态 (不变) ---
const containerRef = ref<HTMLDivElement | null>(null);
const imageRef = ref<HTMLImageElement | null>(null);
const imgRenderedWidth = ref<number>(0);
const imgRenderedHeight = ref<number>(0);
const maskAreas = ref<MaskArea[]>([]);
const visibleAreaIds = ref(new Set<number>()); // 用于 [显示/隐藏]
const currentDrawingVerticesPx = ref<{ x: number; y: number }[]>([]);
const currentDrawingVerticesReal = ref<{ x: number; y: number }[]>([]);

// --- **已修改**: 子弹窗 (顶点数据) 状态 ---
const vertexDataDialogVisible = ref(false); // 替换 shieldedPointsDialogVisible
const currentVertexData = ref<Vertex[]>([]); // 替换 shieldedPointsData
const currentDataAreaName = ref("");

// --- 核心转换逻辑 (不变) ---
const pixelToReal = (px: number, py: number): { x: number; y: number } => {
  if (imgRenderedWidth.value === 0 || imgRenderedHeight.value === 0) return { x: 0, y: 0 };
  const xRatio = px / imgRenderedWidth.value;
  const yRatio = py / imgRenderedHeight.value;
  const realX = REAL_X_MIN + (xRatio * REAL_WIDTH);
  const realY = REAL_Y_MAX - (yRatio * REAL_HEIGHT);
  return { x: realX, y: realY };
};
const realToPixel = (realX: number, realY: number): { x: number; y: number } => {
  if (imgRenderedWidth.value === 0 || imgRenderedHeight.value === 0) return { x: 0, y: 0 };
  const xRatio = (realX - REAL_X_MIN) / REAL_WIDTH;
  const yRatio = (REAL_Y_MAX - realY) / REAL_HEIGHT;
  const px = xRatio * imgRenderedWidth.value;
  const py = yRatio * imgRenderedHeight.value;
  return { x: px, y: py };
};

// --- 暴露给父组件调用 (不变) ---
const open = () => {
  visible.value = true;
};
const close = () => {
  if (isDrawingMode.value) {
    ElMessageBox.confirm('您有未保存的绘制，确定要关闭吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      visible.value = false;
    }).catch(() => {});
  } else {
    visible.value = false;
  }
};
defineExpose({ open, close });

// --- API 调用 (已移除 handleViewData) ---
const fetchMaskAreas = async () => {
  isLoading.value = true;
  try {
    const response = await axios.get<MaskArea[]>('/get_maskareas/');
    maskAreas.value = response.data;
  } catch (error) {
    console.error('获取屏蔽区域列表失败:', error);
    ElMessage.error('获取屏蔽区域列表失败');
  } finally {
    isLoading.value = false;
  }
};

const handleSaveDrawing = async () => {
  // ... (逻辑同上, 保持不变)
  if (currentDrawingVerticesReal.value.length < 3) {
    ElMessage.error('请至少绘制一个三角形（3个点）');
    return;
  }
  if (form.value.name.trim() === "") {
    ElMessage.error('请输入屏蔽区域名称');
    return;
  }
  const first = currentDrawingVerticesReal.value[0];
  const last = currentDrawingVerticesReal.value[currentDrawingVerticesReal.value.length - 1];
  if (first.x !== last.x || first.y !== last.y) {
    currentDrawingVerticesReal.value.push(first);
  }
  const payload = {
    name: form.value.name,
    vertices: currentDrawingVerticesReal.value,
  };
  isLoading.value = true;
  try {
    const response = await axios.post<MaskArea>('/save_maskares/', payload);
    if (response.status === 201) {
      ElMessage.success('保存成功');
      maskAreas.value.push(response.data);
      isDrawingMode.value = false;
      clearDrawing();
      visibleAreaIds.value.add(response.data.id); // 自动显示
    } else {
      ElMessage.error('保存失败，服务器返回异常');
    }
  } catch (error) {
    console.error('保存屏蔽区域失败:', error);
    ElMessage.error('保存失败，请检查网络或联系管理员');
  } finally {
    isLoading.value = false;
  }
};

const handleDeleteArea = async (row: MaskArea) => {
  // ... (逻辑同上, 保持不变)
  try {
    await ElMessageBox.confirm(`确定要删除 "${row.name}" 吗？`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    isLoading.value = true;
    const response = await axios.delete(`/delete_maskares/${row.id}/`);
    if (response.status === 200) {
      ElMessage.success('删除成功 (mock)');
      maskAreas.value = maskAreas.value.filter(area => area.id !== row.id);
      visibleAreaIds.value.delete(row.id); // 取消显示
    } else {
       ElMessage.error('删除失败，服务器返回异常');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  } finally {
    isLoading.value = false;
  }
};

// --- **已修改**: [数据] 按钮功能 ---
const handleViewVertexData = (row: MaskArea) => {
  // **不需要 API 调用**
  // 数据 (row.vertices) 已经在这里了
  currentDataAreaName.value = row.name;
  currentVertexData.value = row.vertices;
  vertexDataDialogVisible.value = true;
};

// 辅助函数：格式化坐标显示
const formatCoordinate = (row: Vertex, column: any, cellValue: number) => {
  return cellValue.toFixed(2); // 保留两位小数
};


// --- 绘图与交互 (基本不变) ---

const displayedPolygonPoints = computed(() => {
  const idToIndexMap = new Map<number, number>();
  maskAreas.value.forEach((area, index) => {
    idToIndexMap.set(area.id, index);
  });

  return maskAreas.value
    .filter(area => visibleAreaIds.value.has(area.id))
    .map(area => {
      const points = area.vertices
        .map(v => realToPixel(v.x, v.y))
        .map(p => `${p.x},${p.y}`)
        .join(' ');
      
      const colorIndex = idToIndexMap.get(area.id) || 0;
      const color = COLORS[colorIndex % COLORS.length];
      
      return { 
        id: area.id,
        points, 
        color 
      };
    });
});

const currentDrawingPolygonPoints = computed(() => {
  return currentDrawingVerticesPx.value.map(v => `${v.x},${v.y}`).join(' ');
});

const handleDrawClick = (event: MouseEvent) => {
  if (!isDrawingMode.value) return; 
  const rect = (event.target as SVGSVGElement).getBoundingClientRect();
  const px = event.clientX - rect.left;
  const py = event.clientY - rect.top;
  const realCoords = pixelToReal(px, py);
  currentDrawingVerticesPx.value.push({ x: px, y: py });
  currentDrawingVerticesReal.value.push(realCoords);
};

const handleVertexClick = (index: number) => {
  if (!isDrawingMode.value) return;
  if (index === 0 && currentDrawingVerticesPx.value.length >= 3) {
    currentDrawingVerticesPx.value.push(currentDrawingVerticesPx.value[0]);
    currentDrawingVerticesReal.value.push(currentDrawingVerticesReal.value[0]);
    ElMessage.success('多边形已闭合');
  }
};

const clearDrawing = () => {
  currentDrawingVerticesPx.value = [];
  currentDrawingVerticesReal.value = [];
};

// **新**: [显示/隐藏] 按钮功能
const toggleAreaVisibility = (area: MaskArea) => {
  if (isDrawingMode.value) {
    ElMessage.warning("请先完成或取消绘制");
    return;
  }
  if (visibleAreaIds.value.has(area.id)) {
    visibleAreaIds.value.delete(area.id);
  } else {
    visibleAreaIds.value.add(area.id);
  }
};

const tableRowClassName = ({ row }: { row: MaskArea }) => {
  if (visibleAreaIds.value.has(row.id)) {
    return 'visible-row'; // 高亮可见行
  }
  return '';
};

const handleStartNew = () => {
  if (isDrawingMode.value) return;
  isDrawingMode.value = true;
  clearDrawing();
  form.value.name = ""; 
};

const handleCancelDrawing = () => {
  isDrawingMode.value = false;
  clearDrawing();
};

// --- 响应式与布局 (不变) ---
const onDialogOpen = () => {
  isDrawingMode.value = false;
  clearDrawing();
  visibleAreaIds.value.clear(); 
  
  fetchMaskAreas();
  
  setTimeout(() => {
    updateImageDimensions();
  }, 50);
};

const updateImageDimensions = () => {
  if (!imageRef.value) return;
  imgRenderedWidth.value = imageRef.value.clientWidth;
  imgRenderedHeight.value = imageRef.value.clientHeight;
};

let resizeObserver: ResizeObserver;
onMounted(() => {
  if (containerRef.value) {
    resizeObserver = new ResizeObserver(() => {
      updateImageDimensions();
    });
    resizeObserver.observe(containerRef.value);
  }
});

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
});
</script>

<style>
/* 穿透修改 el-dialog 样式 */
.mask-area-dialog .el-dialog__body {
  padding: 0 !important;
  height: 80vh; 
}

/* 为可见行添加高亮背景 */
.area-table .visible-row > td {
  background-color: var(--el-color-primary-light-9) !important;
}

</style>

<style scoped>
/* (样式与上一版完全相同，这里省略以节约篇幅) */
.dialog-container {
  height: 100%;
}
.aside-panel {
  border-right: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
}
.aside-header {
  padding: 15px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.aside-header .el-button {
  margin-left: 0; 
}
.area-table {
  width: 100%;
}
:deep(.area-table .el-table__row) {
  cursor: default;
}
.main-panel {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.drawing-controls, .view-controls {
  padding: 10px 15px;
  border-bottom: 1px solid var(--el-border-color);
  flex-shrink: 0;
  background-color: #fcfcfc;
  height: 52px;
  display: flex;
  align-items: center;
}
.drawing-controls .el-form-item {
  margin-bottom: 0;
}
.drawing-container {
  position: relative;
  width: 100%;
  flex-grow: 1; 
  overflow: auto; 
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
}
.background-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  display: block;
}
.drawing-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.drawing-overlay.is-drawing {
  cursor: crosshair;
}
.polygon-view {
  stroke-width: 2;
  transition: all 0.2s ease-in-out;
}
.polygon-draw {
  fill: rgba(64, 158, 255, 0.3);
  stroke: #409eff;
  stroke-width: 2;
  stroke-dasharray: 5, 5;
}
.vertex-point {
  fill: #fff;
  stroke: #409eff;
  stroke-width: 2;
  cursor: pointer;
}
.vertex-start {
  fill: #f56c6c;
  stroke: #fff;
  stroke-width: 2;
  cursor: pointer;
}
</style>